import React from 'react';
import { StyleSheet, TouchableOpacity, StyleProp, ViewStyle, TextStyle } from 'react-native';
import { MaterialIcons } from '@expo/vector-icons';
import * as Linking from 'expo-linking';
import * as Haptics from 'expo-haptics';
import { ThemedText } from './ThemedText';
import { useTheme } from './theme/ThemeContext';

interface ExternalLinkProps {
  href: string;
  children: string;
  style?: StyleProp<ViewStyle>;
  textStyle?: StyleProp<TextStyle>;
  showIcon?: boolean;
}

export function ExternalLink({ 
  href, 
  children, 
  style, 
  textStyle,
  showIcon = true 
}: ExternalLinkProps) {
  const { theme } = useTheme();

  const handlePress = React.useCallback(async () => {
    try {
      // 触觉反馈
      await Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
      // 打开链接
      await Linking.openURL(href);
    } catch (error) {
      console.error('Error opening link:', error);
    }
  }, [href]);

  return (
    <TouchableOpacity
      style={[styles.container, style]}
      onPress={handlePress}
      activeOpacity={0.7}
    >
      <ThemedText
        variant="body"
        style={textStyle}
      >
        {children}
      </ThemedText>
      {showIcon && (
        <MaterialIcons
          name="open-in-new"
          size={16}
          color={theme.colors.primary}
          style={styles.icon}
        />
      )}
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    alignItems: 'center',
    alignSelf: 'flex-start',
  } as ViewStyle,
  text: {
    textDecorationLine: 'underline',
  } as TextStyle,
  icon: {
    marginLeft: 4,
  } as ViewStyle,
});
